package common;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ibm.icu.util.Calendar;

/**
 * 日期处理工具类
 * 
 * @author Administrator
 * 
 */
public class DateUtils {

	private static final Logger log = LoggerFactory.getLogger(DateUtils.class);

	/**
	 * 将字符串转换为日期格式
	 * 
	 * @param date
	 * @return
	 */
	public static Date parseDate(String dateStr, String format) {
		Date date = null;
		try {
			date = new SimpleDateFormat(format).parse(dateStr);
			log.info(dateStr);
			log.info(getFormatDate(date, "yyyy-MM-dd HH:00:00"));
		} catch (ParseException e) {
			log.error(e.getMessage());
			e.printStackTrace();
		}
		return date;
	}

	/**
	 * 将日期转换为制定格式
	 * 
	 * @param date
	 * @param pattern
	 * @return
	 */
	public static String getFormatDate(Date date, String pattern) {
		SimpleDateFormat sdf = new SimpleDateFormat(pattern);
		return sdf.format(date);
	}

	/**
	 * 获取当前
	 * 
	 * @return
	 */
	public static Date getCurrentDate() {
		return Calendar.getInstance().getTime();
	}

	/**
	 * 获取相隔时段
	 * 
	 * @param d1
	 * @param d2
	 * @param field
	 * @return
	 */
	public static int getDiff(Date d1, Date d2, int field) {
		Calendar c = Calendar.getInstance();
		c.setTime(d1);
		return c.fieldDifference(d2, field);
	}

	/**
	 * 获取相隔时段
	 * 
	 * @param d1
	 * @param d2
	 * @return 
	 *         时间间隔小于1分钟返回”1分钟“，大于1分钟并且小于1小时返回"xx分钟”，大于1小时且小于1天返回“xx小时”,大于1天小于1个月
	 *         显示”xx天“，大于1个月且小于1年显示 “xx月” 大于1年显示“xx年”
	 */
	public static String getDiffString(Date d1, Date d2) {
		int[] fieldArray = { Calendar.YEAR, Calendar.MONTH, Calendar.DATE,
				Calendar.HOUR, Calendar.MINUTE, Calendar.SECOND };
		int fieldState = 0;
		int diffNum = 0;
		for (int field : fieldArray) {
			diffNum = getDiff(d1, d2, field);
			if (diffNum > 0) {
				fieldState = field;
				break;
			}
		}
		String format = null;
		switch (fieldState) {
		case Calendar.YEAR:
			format = "年";
			break;
		case Calendar.MONTH:
			format = "月";
			break;
		case Calendar.DATE:
			format = "天";
			break;
		case Calendar.HOUR:
			format = "小时";
			break;
		case Calendar.MINUTE:
			format = "分钟";
			break;
		case Calendar.SECOND:
			diffNum = 1;
			format = "分钟";
			break;
		}
		return diffNum + format;
	}

	/**
	 * 返回当月的首日和末日
	 * 
	 * @return
	 */
	public static Date[] getStartDateAndEndDateOfCurMonth() {
		Calendar c = Calendar.getInstance();
		c.set(Calendar.DATE, 1);
		Date startDate = c.getTime();
		c.set(Calendar.DATE, c.getActualMaximum(Calendar.DATE));
		Date endDate = c.getTime();
		return new Date[] { startDate, endDate };
	}

	public static void main(String[] args) {
		System.out.println(getDiffString(new Date(1348041039000l), new Date(
				1348044639000l)));
	}

}
